#iounit.py
import sys,os,time,struct,io
from subprocess import PIPE,Popen


class IoUnit():
	def __init__(self,obj):
		if type(obj)==Popen:
			self.reader=obj.stdout
			self.writer=obj.stdin
		else:
			self.reader=obj.stdin.buffer
			self.writer=obj.stdout.buffer

	def sendLine(self,data):
		fp=self.writer
		size=len(data)
		buffer=struct.pack('i%ss'%size,size,bytes(data,encoding='utf-8'))
		fp.write(buffer)
		fp.flush()
	def sendBytes(self,data):		
		fp=self.writer
		size=len(data)
		buffer=struct.pack('i%ss'%size,size,data)
		fp.write(buffer)
		fp.flush()
	def readBytes(self):		
		fp=self.reader
		data=fp.read(4)
		if len(data)!=4:return None
		(size,)=struct.unpack('i',data)
		data= fp.read(size)
		return data
	def readLine(self):
		return self.reader.readline()


if __name__=="__main__":
	proc=Popen("cmd",stdin=PIPE,stdout=PIPE,shell=True)
	iu=IoUnit(proc)